package com.hjq.demo.yuliao.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.view.View
import com.bumptech.glide.Glide
import com.dylanc.mmkv.MMKVOwner
import com.hjq.base.BaseDialog
import com.hjq.demo.R
import com.hjq.demo.app.vb.AppVbActivity
import com.hjq.demo.databinding.ActivityUserinfoBinding
import com.hjq.demo.ui.activity.ImagePreviewActivity
import com.hjq.demo.ui.dialog.DateDialog
import com.hjq.demo.ui.dialog.InputDialog
import com.hjq.demo.ui.dialog.SelectDialog
import com.hjq.demo.yuliao.api.GetUserinfoApi
import com.hjq.http.model.FileContentResolver
import java.io.File
import java.net.URI
import java.net.URISyntaxException
import java.util.*

/**
 *
 * @author jiahe
 * 创建日期 2022/2/9
 * 描述 编辑资料
 *
 */
class UserinfoActivity : AppVbActivity<ActivityUserinfoBinding>(), MMKVOwner {

    companion object {

        private const val INTENT_KEY_INFO: String = "info"

        fun start(context: Context, info: String) {
            val intent = Intent(context, UserinfoActivity::class.java)
            intent.putExtra(INTENT_KEY_INFO, info)
            context.startActivity(intent)
        }
    }

    /** 头像地址 */
    private var avatarUrl: Uri? = null


    override fun initView() {
        setOnClickListener(
            binding.ivUserHead,
            binding.sbHead,
            binding.sbNickname,
            binding.sbSex,
            binding.sbBirthday,
            binding.sbDescribe
        )
    }

    override fun initData() {
        val userinfo = kv.decodeParcelable("userinfo", GetUserinfoApi.UserInfo::class.java)

        // 头像
        Glide.with(this)
            .load(userinfo?.avatar_url)
            .placeholder(R.drawable.avatar_placeholder_ic)
            .error(R.drawable.avatar_placeholder_ic)
            .circleCrop()
            .into(binding.ivUserHead)
        binding.sbNickname.setRightText(userinfo?.name)
        binding.sbSex.setRightText(userinfo?.gender)
        binding.sbBirthday.setRightText(userinfo?.age)
        binding.tvDescrib.text = userinfo?.introduce
    }

    override fun onClick(view: View) {
        super.onClick(view)
        if (view === binding.sbHead) {
            ImageSelectVbActivity.start(this, object : ImageSelectVbActivity.OnPhotoSelectListener {

                override fun onSelected(data: MutableList<String>) {
                    // 裁剪头像
                    cropImageFile(File(data[0]))
                }
            })
        } else if (view === binding.ivUserHead) {
            if (avatarUrl != null) {
                // 查看头像
                ImagePreviewActivity.start(this, avatarUrl.toString())
            } else {
                binding.sbHead.let {
                    // 选择头像
                    onClick(it)
                }
            }
        } else if (view === binding.sbNickname) {
            InputDialog.Builder(this)
                .setTitle(getString(R.string.personal_data_name_hint))
                .setContent(binding.sbNickname.getRightText()) //.setHint(getString(R.string.personal_data_name_hint))
                //.setConfirm("确定")
                // 设置 null 表示不显示取消按钮
                //.setCancel("取消")
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .setListener(object : InputDialog.OnListener {

                    override fun onConfirm(dialog: BaseDialog?, content: String) {
                        binding.sbNickname.let {
                            if (it.getRightText() != content) {
                                it.setRightText(content)
                            }
                        }
                    }
                })
                .show()
        } else if (view == binding.sbSex) {
            // 单选对话框
            SelectDialog.Builder(this)
                .setTitle("请选择你的性别")
                .setList("男", "女")
                // 设置单选模式
                .setSingleSelect()
                // 设置默认选中
                .setSelect(0)
                .setListener(object : SelectDialog.OnListener<String> {

                    override fun onSelected(dialog: BaseDialog?, data: HashMap<Int, String>) {
                        toast("确定了：$data")
                    }

                    override fun onCancel(dialog: BaseDialog?) {
                        toast("取消了")
                    }
                })
                .show()
        } else if (view == binding.sbBirthday) {
            // 日期选择对话框
            DateDialog.Builder(this)
                .setTitle(getString(R.string.date_title))
                // 确定按钮文本
                .setConfirm(getString(R.string.common_confirm))
                // 设置 null 表示不显示取消按钮
                .setCancel(getString(R.string.common_cancel))
                // 设置日期
                //.setDate("2018-12-31")
                //.setDate("20181231")
                //.setDate(1546263036137)
                // 设置年份
                //.setYear(2018)
                // 设置月份
                //.setMonth(2)
                // 设置天数
                //.setDay(20)
                // 不选择天数
                //.setIgnoreDay()
                .setListener(object : DateDialog.OnListener {

                    override fun onSelected(dialog: BaseDialog?, year: Int, month: Int, day: Int) {
                        toast(
                            year.toString() + getString(R.string.common_year) + month +
                                    getString(R.string.common_month) + day + getString(R.string.common_day)
                        )

                        // 如果不指定时分秒则默认为现在的时间
                        val calendar: Calendar = Calendar.getInstance()
                        calendar.set(Calendar.YEAR, year)
                        // 月份从零开始，所以需要减 1
                        calendar.set(Calendar.MONTH, month - 1)
                        calendar.set(Calendar.DAY_OF_MONTH, day)
                        toast("时间戳：" + calendar.timeInMillis)
                        //toast(new SimpleDateFormat("yyyy年MM月dd日 kk:mm:ss").format(calendar.getTime()));
                    }

                    override fun onCancel(dialog: BaseDialog?) {
                        toast("取消了")
                    }
                })
                .show()
        } else if (view == binding.sbDescribe) {
            InputDialog.Builder(this)
                .setTitle("介绍一下自己吧")
                .setContent(binding.sbDescribe.getRightText()) //.setHint(getString(R.string.personal_data_name_hint))
                //.setConfirm("确定")
                // 设置 null 表示不显示取消按钮
                //.setCancel("取消")
                // 设置点击按钮后不关闭对话框
                //.setAutoDismiss(false)
                .setListener(object : InputDialog.OnListener {

                    override fun onConfirm(dialog: BaseDialog?, content: String) {
                        binding.sbDescribe.let {
                            if (it.getRightText() != content) {
                                it.setRightText(content)
                            }
                        }
                    }
                })
                .show()
        }
    }

    /**
     * 裁剪图片
     */
    private fun cropImageFile(sourceFile: File) {
        ImageCropVbActivity.start(this, sourceFile, 1, 1, object : ImageCropVbActivity.OnCropListener {

            override fun onSucceed(fileUri: Uri, fileName: String) {
                val outputFile: File = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    FileContentResolver(getActivity(), fileUri, fileName)
                } else {
                    try {
                        File(URI(fileUri.toString()))
                    } catch (e: URISyntaxException) {
                        e.printStackTrace()
                        File(fileUri.toString())
                    }
                }
//                updateCropImage(outputFile, true)

                toast("调用上传图片接口")
                outputFile.delete()
            }

            override fun onError(details: String) {
                // 没有的话就不裁剪，直接上传原图片
                // 但是这种情况极其少见，可以忽略不计
//                updateCropImage(sourceFile, false)

                toast("调用上传图片接口")
                sourceFile.delete()
            }
        })
    }
}